package region

import (
	"context"
	"strings"

	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/setting/rpc/settingclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateRegionLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateRegionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateRegionLogic {
	return &CreateRegionLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateRegionLogic) CreateRegion(req *types.CreateRegionReq) (resp *types.BaseMsgResp, err error) {
	if req.Name == nil || len(strings.TrimSpace(*req.Name)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "region.nameRequired"))
	}

	if req.Code == nil || len(strings.TrimSpace(*req.Code)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "region.codeRequired"))
	}

	res, err := l.svcCtx.SettingRpc.BackendCreateRegion(l.ctx, &settingclient.RegionInfo{
		ParentId: req.ParentId,
		Sort:     req.Sort,
		Name:     req.Name,
		Code:     req.Code,
		Region:   req.Region,
		Status:   req.Status,
	})
	if err != nil {
		return
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
